package com.junwell.controller;


import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.junwell.aspect.LogSys;
import com.junwell.common.dto.LoginDto;
import com.junwell.common.lang.Result;
import com.junwell.entity.Driver;
import com.junwell.entity.Manager;
import com.junwell.entity.User;
import com.junwell.service.DriverService;
import com.junwell.service.ManagerService;
import com.junwell.service.UserService;
import com.junwell.util.JwtUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.HttpServletResponse;


/**
 * @RestController
 * @Controller+@RequestBody 返回json
 */
@RestController
public class AccountController {

    @Autowired
    private ManagerService managerService;

    @Autowired
    private DriverService driverService;

    @Autowired
    private UserService userService;


    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private JedisPool jedisPool;

    @LogSys("登入")
    @PostMapping("/login")
    public Result login(@Validated @RequestBody  LoginDto loginDto, HttpServletResponse response){


        if (loginDto.getRadio().equals("1")){
            Manager manager = managerService.getOne(new QueryWrapper<Manager>().eq("login_name", loginDto.getLoginName()));
            Assert.notNull(manager,"管理员不存在");//断言拦截
            if (!manager.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))){
                return Result.fail("密码不正确");
            }


            String jwt = jwtUtils.generateMToken(manager.getId());

            response.setHeader("Authorization",jwt);
            response.setHeader("Access-control-Expose-Headers","Authorization");

            Jedis jedis = jedisPool.getResource();
            Boolean flag = jedis.exists(manager.getLoginName());
            if (flag){
                return Result.fail("管理员已登录，请勿重复登录");
            }else {
                System.out.println(jedis.set(manager.getLoginName(), "管理员"));
                return Result.succ(MapUtil.builder()
                        .put("id",manager.getId())
                        .put("loginName",manager.getLoginName())
                        .put("password",manager.getPassword())
                        .map()
                );
            }



        }else if (loginDto.getRadio().equals("2")){
            Driver driver = driverService.getOne(new QueryWrapper<Driver>().eq("login_name", loginDto.getLoginName()));
            Assert.notNull(driver,"员工不存在");
            if (!driver.getPassword().equals(loginDto.getPassword())){
                return Result.fail("密码不正确");
            }
            String jwt= jwtUtils.generateDToken(driver.getId());
            response.setHeader("Authorization",jwt);
            response.setHeader("Access-control-Expose-Headers","Authorization");


            Jedis jedis = jedisPool.getResource();
            Boolean flag = jedis.exists(driver.getLoginName());
            if (flag){
                return Result.fail("员工已登录，请勿重复登录");
            }else{
                System.out.println(jedis.set(driver.getLoginName(), "员工"));
                return Result.succ(MapUtil.builder()
                        .put("id",driver.getId())
                        .put("name",driver.getName())
                        .put("login_name",driver.getLoginName())
                        .put("password",driver.getPassword())
                        .put("sex",driver.getSex())
                        .put("age",driver.getAge())
                        .put("phonenumber",driver.getPhonenumber())
                        .put("entry_day",driver.getEntryDay())
                        .put("workarea",driver.getWorkarea())
                        .map()
                );
            }


        }else {
            User user = userService.getOne(new QueryWrapper<User>().eq("login_name", loginDto.getLoginName()));
            Assert.notNull(user,"用户不存在");
            if (!user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))){
                return  Result.fail("密码不正确");
            }
            String jwt = jwtUtils.generateUToken(user.getId());
            response.setHeader("Authorization",jwt);
            response.setHeader("Access-control-Expose-Headers","Authorization");
            Jedis jedis = jedisPool.getResource();
            Boolean flag = jedis.exists(user.getLoginName());
            if (flag){
                return Result.fail("用户已登录，请勿重复登录");
            }else {
                System.out.println(jedis.set(user.getLoginName(), "用户"));
                return Result.succ(MapUtil.builder()
                        .put("id",user.getId())
                        .put("name",user.getName())
                        .put("loginName",user.getLoginName())
                        .put("password",user.getPassword())
                        .put("age",user.getAge())
                        .put("birthday",user.getBirthday())
                        .put("gender",user.getGender())
                        .put("phonenumber",user.getPhonenumber())
                        .put("address",user.getAddress())
                        .map()
                );
            }


        }
    }

    /**/


    @LogSys("登出")
    @GetMapping("/logout/{loginName}")
    public Result logout(@PathVariable("loginName")String loginName){
        SecurityUtils.getSubject().logout();
        Jedis jedis = jedisPool.getResource();
        System.out.println(jedis.del(loginName));
        jedis.close();
        return Result.succ("登出");


    }

}
